<?php
/**
 * 
 *
 * @category   Application_Extensions
 * @package    Recorder
 * @copyright  Copyright 2006-2010 Idragonsolution Developments
 * @license    http://idragonsolution.com/
 * @version    $Id: Bootstrap.php 9747 2012-07-26 02:08:08Z Thien $
 * @author     Thien
 */
class Paint_Api_Core extends Core_Api_Abstract
{
    // handle recorder upload
  public function createPaint($file, $params = array())
  {
    $name = 'canvas'.time().'.png';
    $path = APPLICATION_PATH.DS.'public'.DS.'paints';
    if(!file_exists($params)){
        mkdir($path,0777,true);
    }
    $path = $path.DS.$name;
    
	$data = substr($file, strpos($file, ",") + 1);
	$decodedData = base64_decode($data);
	$fp = fopen($path, 'wb');
	fwrite($fp, $decodedData);
	fclose();
	
    $file = array('tmp_name' => $path);
    $file['name'] = $name;
    $file['type'] = 'image/png';
    
    // upload to storage system
    $params = array_merge(array(
      'type' => 'paint',
      'name' => $name,
      'parent_type' => 'paint',
      'parent_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
      'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
      'extension' => 'png',
      'mime_major' => 'image',
      'mime_minor' => 'png',
    ), $params);

    $paint = Engine_Api::_()->storage()->create($file, $params);

    return $paint;
  }
  
  
  public function getRating($paint_id)
  {
    $table  = Engine_Api::_()->getDbTable('ratings', 'paint');
    $rating_sum = $table->select()
      ->from($table->info('name'), new Zend_Db_Expr('SUM(rating)'))
      ->group('paint_id')
      ->where('paint_id = ?', $paint_id)
      ->query()
      ->fetchColumn(0)
      ;

    $total = $this->ratingCount($paint_id);
    if ($total) $rating = $rating_sum/$this->ratingCount($paint_id);
    else $rating = 0;
    
    return $rating;
  }

  public function getRatings($paint_id)
  {
    $table  = Engine_Api::_()->getDbTable('ratings', 'paint');
    $rName = $table->info('name');
    $select = $table->select()
                    ->from($rName)
                    ->where($rName.'.paint_id = ?', $paint_id);
    $row = $table->fetchAll($select);
    return $row;
  }
  
  public function checkRated($paint_id, $user_id)
  {
    $table  = Engine_Api::_()->getDbTable('ratings', 'paint');

    $rName = $table->info('name');
    $select = $table->select()
                 ->setIntegrityCheck(false)
                    ->where('paint_id = ?', $paint_id)
                    ->where('user_id = ?', $user_id)
                    ->limit(1);
    $row = $table->fetchAll($select);
    
    if (count($row)>0) return true;
    return false;
  }
   
  public function deletePaint($paint)
  {

    // delete paint ratings
    Engine_Api::_()->getDbtable('ratings', 'paint')->delete(array(
      'paint_id = ?' => $paint->paint_id,
    ));

   
    
    // delete activity feed and its comments/likes
    $item = Engine_Api::_()->getItem('paint', $paint->paint_id);
    if ($item) {
      $item->delete();
    }


  }
    
  public function setRating($paint_id, $user_id, $rating){
    $table  = Engine_Api::_()->getDbTable('ratings', 'paint');
    $rName = $table->info('name');
    $select = $table->select()
                    ->from($rName)
                    ->where($rName.'.paint_id = ?', $paint_id)
                    ->where($rName.'.user_id = ?', $user_id);
    $row = $table->fetchRow($select);
    
    if (!$row  ) {
      // create rating
      Engine_Api::_()->getDbTable('ratings', 'paint')->insert(array(
        'paint_id' => $paint_id,
        'user_id' => $user_id,
        'rating' => $rating
      ));
    }
/*
    $select = $table->select()
      //->setIntegrityCheck(false)
      ->from($rName)
      ->where($rName.'.video_id = ?', $video_id);

    $row = $table->fetchAll($select);
    $total = count($row);
    foreach( $row as $item )
    {
      $rating += $item->rating;
    }
    $video = Engine_Api::_()->getItem('video', $video_id);
    $video->rating = $rating/$total;
    $video->save();*/
    
  }

  public function ratingCount($paint_id){
    $table  = Engine_Api::_()->getDbTable('ratings', 'paint');
    $rName = $table->info('name');
    $select = $table->select()
                    ->from($rName)
                    ->where($rName.'.paint_id = ?', $paint_id);
    $row = $table->fetchAll($select);
    $total = count($row);
    return $total;
  }
  
  public function getCategories()
  {
    $table = Engine_Api::_()->getDbTable('categories', 'paint');
    return $table->fetchAll($table->select()->order('category_name ASC'));
  }

  public function getCategory($category_id)
  {
    return Engine_Api::_()->getDbtable('categories', 'paint')->find($category_id)->current();
  }
  
  public function getPaintsPaginator($params = array())
  {
    $paginator = Zend_Paginator::factory($this->getPaintsSelect($params));
    if( !empty($params['page']) )
    {
      $paginator->setCurrentPageNumber($params['page']);
    }
    if( !empty($params['limit']) )
    {
      $paginator->setItemCountPerPage($params['limit']);
    }
    return $paginator;
  }

  public function getPaintsSelect($params = array())
  {
    $table = Engine_Api::_()->getDbtable('paints', 'paint');
    $rName = $table->info('name');

    $tmTable = Engine_Api::_()->getDbtable('TagMaps', 'core');
    $tmName = $tmTable->info('name');
    
    $select = $table->select()
      ->from($table->info('name'))
      ->where('search = ?',1)
      ->order( !empty($params['orderby']) ? $params['orderby'].' DESC' : "$rName.creation_date DESC" );
    
    if( !empty($params['text']) ) {
      $searchTable = Engine_Api::_()->getDbtable('search', 'core');
      $db = $searchTable->getAdapter();
      $sName = $searchTable->info('name');
      $select
        ->joinRight($sName, $sName . '.id=' . $rName . '.paint_id', null)
        ->where($sName . '.type = ?', 'paint')
        ->where(new Zend_Db_Expr($db->quoteInto('MATCH(' . $sName . '.`title`, ' . $sName . '.`description`, ' . $sName . '.`keywords`, ' . $sName . '.`hidden`) AGAINST (? IN BOOLEAN MODE)', $params['text'])))
        //->order(new Zend_Db_Expr($db->quoteInto('MATCH(' . $sName . '.`title`, ' . $sName . '.`description`, ' . $sName . '.`keywords`, ' . $sName . '.`hidden`) AGAINST (?) DESC', $params['text'])))
        ;
    }
      
    
    if( !empty($params['search']) && is_numeric($params['search']) )
    {
      $select->where($rName.'.search = ?', $params['search']);
    }
    if (!empty($params['search']) && is_string($params['search'])) {
          $select->where('title LIKE ? OR description LIKE ?', '%'.$params['search'].'%');
    }
        
    if( !empty($params['user_id']) && is_numeric($params['user_id']) )
    {
      $select->where($rName.'.owner_id = ?', $params['user_id']);
    }

    if( !empty($params['user']) && $params['user'] instanceof User_Model_User )
    {
      $select->where($rName.'.owner_id = ?', $params['user_id']->getIdentity());
    }
    
    if( !empty($params['category']) )
    {
      $select->where($rName.'.category_id = ?', $params['category']);
    }

    if( !empty($params['tag']) )
    {
      $select
        // ->setIntegrityCheck(false)
        // ->from($rName)
        ->joinLeft($tmName, "$tmName.resource_id = $rName.paint_id", NULL)
        ->where($tmName.'.resource_type = ?', 'paint')
        ->where($tmName.'.tag_id = ?', $params['tag']);
    }

    return $select;
  }
  
}